package com.cloud.logger.zchain.spring.config;

import com.cloud.logger.zchain.core.ChainNode;
import com.cloud.logger.zchain.core.InetAddressUtilities;
import com.cloud.logger.zchain.core.common.entity.AngelaLoggerProject;
import com.cloud.logger.zchain.core.common.entity.AngelaLoggerProjectNode;
import com.cloud.logger.zchain.core.common.properties.ServerInfo;
import com.cloud.logger.zchain.core.common.threadlocal.LoggerThreadLocal;
import com.cloud.logger.zchain.core.constants.Constants;
import com.cloud.logger.zchain.core.zookeeper.LeaderElection;
import com.cloud.logger.zchain.core.zookeeper.ZchainConnectionStateListener;
import com.cloud.logger.zchain.core.zookeeper.ZookeeperFactory;
import com.cloud.logger.zchain.spring.properties.ZchainProperties;
import com.cloud.logger.zchain.zchainclient.util.AngelaAopLogger;
import com.cloud.logger.zchain.zchainclient.util.KafkaUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.framework.recipes.nodes.PersistentEphemeralNode;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

import javax.management.MalformedObjectNameException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Timer;
import java.util.TimerTask;

/**
 * User: wcy
 * Date: 2017/11/27
 * Time: 15:27
 */
@Configuration
@EnableConfigurationProperties(ZchainProperties.class)
public class ZchainClientSpringBootInit implements ApplicationListener<EmbeddedServletContainerInitializedEvent> {

    @Autowired
    private ZchainProperties zchainProperties;

    private static EmbeddedServletContainerInitializedEvent event;

    @Override
    public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
        ZchainClientSpringBootInit.event = event;
        initServer();
        initTask();
    }

    private void initServer() {
        try {
            ServerInfo.setScenic(zchainProperties.getProject().getScenic());
            ServerInfo.setProject(zchainProperties.getProject().getName());
            ServerInfo.setIp(InetAddressUtilities.getLocalHostLANAddress().getHostAddress());
            ServerInfo.setPort(event.getEmbeddedServletContainer().getPort());

            String success = zchainProperties.getCode().getSuccess();
            if(!StringUtils.isEmpty(success)){
                String[] codeArr = success.split(",");
                AngelaAopLogger.RESULT_SUCCESS = new HashSet<String>(Arrays.asList(codeArr));
            }
            String code = zchainProperties.getCode().getName();
            AngelaAopLogger.RESULT_CODE = StringUtils.isEmpty(code)?AngelaAopLogger.RESULT_CODE:code;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void initTask() {

        KafkaUtil.startProject();
        AngelaLoggerProjectNode project = LoggerThreadLocal.getCurrentProject();
        //当spring容器初始化完成后就会执行该方法。
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {

                KafkaUtil.checkKafka();
            }
        }, 60 * 1000, 120*60 * 1000);

        ZookeeperFactory zookeeperFactory = ZookeeperFactory.getInstance();
        try {
            zookeeperFactory.init(zchainProperties.getZookeeper().getHost(),zchainProperties.getZookeeper().getNameSpace(),zchainProperties.getZookeeper().getConnectionTimeOut());
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            zookeeperFactory.createProjectNode( project);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
